package com.hoow.shakoow.shake

import android.annotation.SuppressLint
import android.graphics.Typeface
import android.os.*
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.hoow.shakoow.R
import com.hoow.shakoow.ai.data.ReqAiBase
import com.hoow.shakoow.ai.data.ReqDeleteGreetRecord
import com.hoow.shakoow.ai.data.ReqDeleteShakeRecord
import com.hoow.shakoow.ai.home.NetworkViewModel
import com.hoow.shakoow.base.BaseActivity
import com.hoow.shakoow.components.dialog.MessageDialog
import com.hoow.shakoow.databinding.ActivityShakeHistoryBinding
import com.hoow.shakoow.enums.PageTagEnum
import com.hoow.shakoow.extend.*
import com.hoow.shakoow.shake.adapter.ShakeHistoryAdapter
import com.hoow.shakoow.utils.analytics.util.AnalyticsUtil
import com.yanzhenjie.recyclerview.OnItemMenuClickListener
import com.yanzhenjie.recyclerview.SwipeMenuCreator
import com.yanzhenjie.recyclerview.SwipeMenuItem
import com.yanzhenjie.recyclerview.SwipeRecyclerView


/** 摇到的人页 */
@SuppressLint("CustomSplashScreen")
class ShakeHistoryActivity : BaseActivity() {

    //布局binding
    private lateinit var mActivityBinding: ActivityShakeHistoryBinding

    // 适配器
    private lateinit var mShakeHistoryAdapter: ShakeHistoryAdapter

    //api接口viewModel
    private val mNetworkViewModel by lazy {
        ViewModelProvider(this)[NetworkViewModel::class.java]
    }

    override fun onBindingViewModel(): List<ViewModel> {
        val list = mutableListOf<ViewModel>()
        list.add(mNetworkViewModel)
        return list
    }

    override fun onBindingViewTag(): String {
        return PageTagEnum.shake_history.name.uppercase()
    }

    override fun onBindingContentView(): View {
        mActivityBinding = ActivityShakeHistoryBinding.inflate(layoutInflater)
        return mActivityBinding.root
    }

    @SuppressLint("SetTextI18n", "SourceLockedOrientationActivity", "NotifyDataSetChanged")
    override fun onContentViewBinded() {
        try {
            // 点击全部清空
            mActivityBinding.topNavBarInfo.setOnActionClickListener { action ->
                if (action == R.integer.NavbarActionRight) {
                    MessageDialog.showDialog(
                        supportFragmentManager,
                        getString(R.string.shake_clean_all_data),
                        getString(R.string.confirm)
                    ) { dialogAction ->
                        if (MessageDialog.ACTION_OK == dialogAction) {
                            var sbIds = ""
                            mNetworkViewModel.mShakeHistoryList.forEach { item ->
                                item.shakeId?.let { vId ->
                                    if (vId.isNotBlank()) {
                                        if (sbIds.isNotBlank()) {
                                            sbIds = "${sbIds},$vId"
                                        } else {
                                            sbIds = vId
                                        }
                                    }
                                }
                            }

                            // 删除数据
                            if (sbIds.isNotBlank()) {
                                mNetworkViewModel.deleteShakeRecord(ReqDeleteShakeRecord(shakeIds = sbIds))
                            }
                        }
                    }

                    // 打点：摇一摇
                    AnalyticsUtil.saveHitPointInfo(
                        type = "SHAKE_HISTORY_CLEAR_ALL_CLICK",
                        remark = ""
                    )
                }
            }

            // 初始化适配器
            mShakeHistoryAdapter = ShakeHistoryAdapter(mNetworkViewModel.mShakeHistoryList)
            mShakeHistoryAdapter.setItemClickListener { i, revObjShakeHistory, isCheckUserInfo ->
                // 更新刷新状态
                mActivityBinding.srlLayout.isRefreshing = false

                // 打点：摇一摇
                AnalyticsUtil.saveHitPointInfo(
                    type = "SHAKE_HISTORY_ITEM_CLICK",
                    remark = ""
                )

                // 组装信息
                ShakeUserManager.mCurUserId = revObjShakeHistory.userId
                ShakeUserManager.mCurShakeId = revObjShakeHistory.shakeId

                val shakeId = revObjShakeHistory.shakeId ?: ""
                val userId = revObjShakeHistory.userId ?: ""
                val sbId = ""
                val params = HashMap<String, String>()
                params["userId"] = userId
                params["shakeId"] = shakeId
                params["sbId"] = sbId

                // 跳转详情页
                startToUserDetailPage(params)

//                if (isCheckUserInfo) {
//                    // 跳转详情页
//                    startToUserDetailPage(params)
//                } else {
//                    // 跳转回复列表页
//                    startToUserChatInfoPage(params)
//                }
            }

            mActivityBinding.rcShakeHistoryList.layoutManager = LinearLayoutManager(this)
            mActivityBinding.rcShakeHistoryList.setSwipeMenuCreator(mSwipeMenuCreator);
            mActivityBinding.rcShakeHistoryList.setOnItemMenuClickListener(mItemMenuClickListener)
            mActivityBinding.rcShakeHistoryList.adapter = mShakeHistoryAdapter

            // 初始化下拉刷新
            mActivityBinding.srlLayout.buildRefreshConfigs(this) {
                // 获取打招呼列表
                mNetworkViewModel.getShakeHistoryList(ReqAiBase(showLoading = false))
            }

            // 删除消息记录返回
            mNetworkViewModel.onDeleteShakeRecordLiveData.observe(this) {
                // 更新刷新状态
                mActivityBinding.srlLayout.isRefreshing = false

                // 获取摇一摇历史列表
                mNetworkViewModel.getShakeHistoryList(ReqAiBase(showLoading = false))
            }

            // 监听接口返回
            mNetworkViewModel.onGetShakeHistoryListLiveData.observe(this) {
                // 更新刷新状态
                mActivityBinding.srlLayout.isRefreshing = false

                if (it.isSuccess) {
                    it.getOrNull()?.let { result ->
                        mNetworkViewModel.mShakeHistoryList.clear()
                        mNetworkViewModel.mShakeHistoryList.addAll(result)

                        // 更新列表
                        mShakeHistoryAdapter.notifyDataSetChanged()

                        // 更新空白页展示
                        if (mNetworkViewModel.mShakeHistoryList.size > 0) {
                            mActivityBinding.emptyLayout.llEmptyList.visibility = View.GONE
                        } else {
                            mActivityBinding.emptyLayout.llEmptyList.visibility = View.VISIBLE
                        }
                    }
                }
            }

            // 获取摇一摇篮历史列表
            mNetworkViewModel.getShakeHistoryList(ReqAiBase())

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * RecyclerView的Item中的Menu
     */
    private val mSwipeMenuCreator =
        SwipeMenuCreator { leftMenu, rightMenu, position ->
            val width = dpToPx(90F)
            val height: Int = ViewGroup.LayoutParams.MATCH_PARENT
            val deleteItem = SwipeMenuItem(this@ShakeHistoryActivity)
            deleteItem.setBackgroundColor(
                ContextCompat.getColor(
                    this@ShakeHistoryActivity,
                    R.color.main_page_background
                )
            )
            deleteItem.setTextColor(ContextCompat.getColor(
                this@ShakeHistoryActivity,
                R.color.white
            ))
            deleteItem.width = width.toInt()
            deleteItem.height = height
            deleteItem.text = getString(R.string.shake_delete)
            deleteItem.textSize = 16
            deleteItem.textTypeface = Typeface.DEFAULT_BOLD
            rightMenu.addMenuItem(deleteItem)
        }

    /**
     * RecyclerView的Item中的Menu点击监听。
     */
    private val mItemMenuClickListener =
        OnItemMenuClickListener { menuBridge, position ->
            menuBridge.closeMenu()
            val direction = menuBridge.direction
            val menuPosition = menuBridge.position
            if (direction == SwipeRecyclerView.RIGHT_DIRECTION) {
                println("===>点击了delete: $position")

                // 删除数据
                if (mNetworkViewModel.mShakeHistoryList.size > position) {
                    val item = mNetworkViewModel.mShakeHistoryList[position]
                    item.shakeId?.let { vId ->
                        mNetworkViewModel.deleteShakeRecord(ReqDeleteShakeRecord(shakeIds = vId))
                    }
                }

                // 打点：摇一摇
                AnalyticsUtil.saveHitPointInfo(
                    type = "SHAKE_HISTORY_ITEM_DELETE_CLICK",
                    remark = ""
                )
            }
        }

    private fun dpToPx(dp: Float): Float {
        val density = resources.displayMetrics.density
        return dp * density
    }
}